package com.intelli4.pos.controllers.impl;

import java.util.Calendar;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.intelli4.pos.controllers.SessionAlreadyOpenedException;
import com.intelli4.pos.controllers.SessionController;
import com.intelli4.pos.controllers.SessionEventManager;
import com.intelli4.pos.core.Operator;
import com.intelli4.pos.core.Session;
import com.intelli4.pos.core.Terminal;
import com.intelli4.pos.events.AfterSessionCloseEvent;
import com.intelli4.pos.events.AfterSessionOpenEvent;
import com.intelli4.pos.events.BeforeSessionCloseEvent;
import com.intelli4.pos.events.BeforeSessionOpenEvent;

public class SessionControllerImpl extends HibernateDaoSupport implements
		SessionController {
	private SessionEventManager eventManager;

	private Terminal terminal;
	private Session currentSession;

	@Override
	public void setEventManager(SessionEventManager eventManager) {
		this.eventManager = eventManager;
	}

	@Override
	public void setTerminal(Terminal terminal) {
		this.terminal = terminal;
	}

	@Override
	public void openNewSession(Operator operator)
			throws SessionAlreadyOpenedException {
		eventManager.fireEvent(new BeforeSessionOpenEvent(currentSession));

		if (currentSession != null)
			throw new SessionAlreadyOpenedException(currentSession);

		currentSession = new Session();
		currentSession.setStartTime(Calendar.getInstance());
		currentSession.setTerminal(terminal);
		currentSession.setOperator(operator);

		getHibernateTemplate().save(currentSession);

		eventManager.fireEvent(new AfterSessionOpenEvent(currentSession));
	}

	@Override
	public void closeCurrentSession() {
		eventManager.fireEvent(new BeforeSessionCloseEvent(currentSession));

		currentSession.setEndTime(Calendar.getInstance());
		getHibernateTemplate().update(currentSession);
		currentSession = null;

		eventManager.fireEvent(new AfterSessionCloseEvent(currentSession));
	}

	@Override
	public Session getCurrentSession() {
		return currentSession;
	}
}
